#!/usr/bin/env python3
"""
自动合并协议表格中的高/低位成对行，并同步修改长度。
用法：python3 scripts/merge_high_low.py config/protocols/monet/monet.md
"""
import sys, re

if len(sys.argv) < 2:
    print("usage: merge_high_low.py file.md")
    sys.exit(2)

path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

out = []
changed = False
row_pat = re.compile(r'^\s*\|.*\|\s*$')
# 只处理有“高位”或“低位”字样的描述列
hi_pat = re.compile(r'高位')
lo_pat = re.compile(r'低位')

skip = False
for i in range(len(lines)):
    if skip:
        skip = False
        continue
    line = lines[i]
    if row_pat.match(line):
        # 拆分单元格
        cells = [c.strip() for c in line.strip().split('|')[1:-1]]
        if len(cells) < 5:
            out.append(line)
            continue
        desc = cells[2]
        # 检查是否为高位
        if hi_pat.search(desc) and i+1 < len(lines):
            next_line = lines[i+1]
            next_cells = [c.strip() for c in next_line.strip().split('|')[1:-1]]
            if len(next_cells) == len(cells):
                next_desc = next_cells[2]
                # 检查后一行为低位且地址连续
                if lo_pat.search(next_desc):
                    # 合并长度
                    try:
                        l1 = int(cells[1])
                        l2 = int(next_cells[1])
                        new_len = str(l1 + l2)
                    except:
                        new_len = cells[1]
                    # 合并描述
                    new_desc = re.sub(r'[高低]位', '', desc+next_desc)
                    # 其它列保留高位行，备注合并
                    new_cells = cells.copy()
                    new_cells[1] = new_len
                    new_cells[2] = new_desc
                    # 合并备注
                    if cells[-1] != next_cells[-1]:
                        new_cells[-1] = cells[-1] + '/' + next_cells[-1]
                    new_line = '| ' + ' | '.join(new_cells) + ' |\n'
                    out.append(new_line)
                    changed = True
                    skip = True
                    continue
    out.append(line)

if changed:
    bak = path + '.bak'
    with open(bak, 'w', encoding='utf-8') as f:
        f.writelines(lines)
    with open(path, 'w', encoding='utf-8') as f:
        f.writelines(out)
    print(f"Merged high/low rows in {path}; backup at {bak}")
else:
    print(f"No changes needed for {path}")
